package com.example.aop.proxy.dynamic;

import com.example.aop.proxy.HouseSubject;
import com.example.aop.proxy.RealHouseSubject;
import org.springframework.cglib.proxy.Enhancer;

import java.lang.reflect.Proxy;

public class Main {
    public static void main(String[] args) {
        HouseSubject houseSubject = new RealHouseSubject();

        // 使用 JDK 动态代理
//        HouseSubject proxy = (HouseSubject) Proxy.newProxyInstance(
//                houseSubject.getClass().getClassLoader(),
//                new Class[]{HouseSubject.class},
//                new HouseInvocationHandler(houseSubject));
//
//        proxy.rentHouse();
//
//        proxy.saleHouse();

        // 使用 CGLIB 动态代理 - 代理接口
        HouseSubject cglibProxy = (HouseSubject) Enhancer.create(
                houseSubject.getClass(), new CGLIBMethodInterceptor(houseSubject));

        cglibProxy.rentHouse();
        cglibProxy.saleHouse();

        // 使用 CGLIB 动态代理 - 代理实体类
        RealHouseSubject realHouseSubject = new RealHouseSubject();
        RealHouseSubject cglibProxy2 = (RealHouseSubject) Enhancer.create(
                realHouseSubject.getClass(), new CGLIBMethodInterceptor(realHouseSubject));

        cglibProxy2.rentHouse();
        cglibProxy2.saleHouse();
    }
}
